/* nighthawk.util.zip
 *
 */
package util

import (
 	"io"
	"os"
	"archive/zip"
	"path/filepath"
)

// Unzip function is copied from following blog
// http://blog.ralch.com/tutorial/golang-working-with-zip/
func Unzip(archive, target string) error {
	reader, err := zip.OpenReader(archive)
	if err != nil {
		return err
	}

	if err := os.MkdirAll(target, 0755); err !=nil {
		return err
	}

	for _,file := range reader.File {
		path := filepath.Join(target, file.Name)
		if file.FileInfo().IsDir() {
			os.MkdirAll(path, file.Mode())
			continue
		}

		fileReader, err := file.Open()
		if err != nil {
			return err
		}
		defer fileReader.Close()

		targetFile, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, file.Mode())
		if err != nil {
			return err
		}
		defer targetFile.Close()

		if _,err := io.Copy(targetFile, fileReader); err != nil {
			return err 
		}
	}
	return nil 
}